package com.dd.seckill.cluster.config.intercepter;

import com.dd.seckill.cluster.config.exception.BusinessException;
import com.dd.seckill.cluster.utils.redisdatainit.UserTokenInitializer;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/7 11:22
 * @Description 权限拦截器
 */
@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

    private final RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        // 模拟验证用户是否已经登陆过 根据token获取用户ID 如果能获取到 则说明登陆过
        Object obj = redisTemplate.opsForValue().get(UserTokenInitializer.REDIS_USERID_KEY_PREFIX + token);
        if (obj != null) {
            return true;
        }
        throw new BusinessException(401, "您尚未登陆，不可执行后续操作");
    }
}